package com.zzuli.yxy.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @auther pony
 * @create 2023-03-05 19:14
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    @Autowired
    private Employee employee;

    private List<String> permissions;

    public LoginUser(Employee employee, List<String> permissions) {
        this.employee = employee;
        this.permissions = permissions;
    }
    /*SimpleGrantedAuthority 在redis序列化会报错，就不让他序列化，可以让permissions存到
    我们在转化为 SimpleGrantedAuthority*/
    @JSONField(serialize = false)
    private  List<GrantedAuthority> authorities;
    //框架是不会调用我们写的list集合获取权限信息的，所以我们要重写下面这个方法
    /**
     * 返回权限信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities!=null){
            return authorities;
        }
        authorities = new ArrayList<>();
        for (String permission: permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
/*        authorities = permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());*/
        return authorities;
    }

    /**
     * 获取密码
     * @return
     */
    @Override
    public String getPassword() {
        return employee.getPassword();
    }

    /**
     * 获取用户信息
     * @return
     */
    @Override
    public String getUsername() {
        return employee.getUsername();
    }

    /**
     * 是否过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否被锁定
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 是否超时
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
